<?php
include_once(SITE_PATH."/ocean/Extend/Library/ORG/Net/UploadFile.class.php");

class XattachService extends Think {

	/**
	 * 上传附件
	 *
	 * @param string $attach_type   附件类型
	 * @param array  $input_options 配置选项[不推荐修改, 默认使用后台的配置]
	 */
	public function upload($attach_type='attach',$input_options=array()) {
		$system_default = model('Data')->lget('attach');
		if ( empty($system_default['attach_path_rule']) || empty($system_default['attach_max_size']) || empty($system_default['attach_allow_extension']) ) {
			$data['attach_path_rule']		 = 'Y/md/H/';
			$data['attach_max_size']		 = '2'; // 默认2M
			$data['attach_allow_extension']  = 'jpg,gif,png,jpeg,bmp,zip,rar,doc,xls,ppt,docx,xlsx,pptx,pdf';
			model('Data')->lput('attach', $data);
			$system_default = $data;
		}

		//载入默认规则
		$default_options =	array();
		$default_options['custom_path']	=	date($system_default['attach_path_rule']);				//应用定义的上传目录规则：'Y/md/H/'
		$default_options['max_size']	=	floatval($system_default['attach_max_size'])*1000000;	//单位: 兆
		$default_options['allow_exts']	=	$system_default['attach_allow_extension']; 				//'jpg,gif,png,jpeg,bmp,zip,rar,doc,xls,ppt,docx,xlsx,pptx,pdf'
		$default_options['allow_types']	=	'';
		$default_options['save_path']	=	UPLOAD_PATH.'/'.$default_options['custom_path'];
		$default_options['save_name']	=	'';
		$default_options['save_rule']	=	'uniqid';
		$default_options['save_to_db']	=	true;

		//定制化设这 覆盖默认设置
		$options	=	array_merge($default_options,$input_options);

		//用户ID
		if( intval($options['uid'])==0 )	$options['uid']	= $_SESSION['mid'];

		//初始化上传参数
        $upload					=	new UploadFile($options['max_size'],$options['allow_exts'],$options['allow_types']);
		//设置上传路径
		$upload->savePath		=	$options['save_path'];
        //启用子目录
		$upload->autoSub		=	false;
		//保存的名字
        $upload->saveName		=   $options['save_name'];
		//默认文件名规则
		$upload->saveRule		=	$options['save_rule'];
        //是否缩略图
        $upload->thumb          =   false;

		//创建目录
		mkdir($upload->savePath,0777,true);
		
		//执行上传操作
        if(!$upload->upload()) {

			//上传失败，返回错误
			$return['status']	=	false;
			$return['info']		=	$upload->getErrorMsg();
			return	$return;

		}else{
			$upload_info	=	$upload->getUploadFileInfo();
			$xattach		=	M('Attach');
			//保存信息到附件表
			if($options['save_to_db']){
				foreach($upload_info as $u){
					$map['attach_type']	=	$attach_type;
					$map['userId']		=	$options['uid'];
					$map['name']		=	$u['name'];
					$map['type']		=	$u['type'];
					$map['size']		=	$u['size'];
					$map['extension']	=	strtolower($u['extension']);
					$map['hash']		=	$u['hash'];
					$map['savepath']	=	$options['custom_path'];
					$map['savename']	=	$u['savename'];
					$map['uploadTime']	=	time();
					$aid		=	$xattach->add($map);
					$map['id']	=	intval($aid);
					$map['key']	=	$u['key'];
					$infos[]	=	$map;
					
					if ($system_default ['attach_watermark_closed'] == 1) {
						include_once(SITE_PATH."/ocean/Extend/Library/ORG/Util/Image2.class.php");
						$size = getimagesize($upload_info[0]['savepath'].$map['savename']);
						if($size[0] > intval($system_default ['attach_watermark_minwidth']) && $size[1] > intval($system_default ['attach_watermark_minheight'])){
							if ($system_default ['attach_watermark_type'] == 'img') {
								Image::waters ( $default_options ['save_path'].$u['savename'], 0, $system_default ['attach_watermark_url'], "", $system_default ['attach_image_thumb_quality'] , intval($system_default ['attach_watermark_place']));
							} else {
								Image::waters ( $default_options ['save_path'].$u['savename'], 1, "","", $system_default ['attach_image_thumb_quality'], intval($system_default ['attach_watermark_place']), $system_default ['attach_watermark_txt'], $system_default ['attach_watermark_fontsize'], './Public/font/simhei.ttf' );
							}
						}
					}
					unset($map);
				}
			}else{
				foreach($upload_info as $u){
					$map['attach_type']	=	$attach_type;
					$map['userId']		=	$options['uid'];
					$map['name']		=	$u['name'];
					$map['type']		=	$u['type'];
					$map['size']		=	$u['size'];
					$map['extension']	=	strtolower($u['extension']);
					$map['hash']		=	$u['hash'];
					$map['savepath']	=	$options['custom_path'];
					$map['savename']	=	$u['savename'];
					$map['uploadTime']	=	time();
					$map['key']	=	$u['key'];
					$infos[]	=	$map;
					
					if ($system_default ['attach_watermark_closed'] == 1) {
						include_once(SITE_PATH."/ocean/Extend/Library/ORG/Util/Image2.class.php");
						$size = getimagesize($upload_info[0]['savepath'].$map['savename']);
						if($size[0] > intval($system_default ['attach_watermark_minwidth']) && $size[1] > intval($system_default ['attach_watermark_minheight'])){
							if ($system_default ['attach_watermark_type'] == 'img') {
								Image::waters ( $default_options ['save_path'] .  $u['savename'], 0, $system_default ['attach_watermark_url'], "", $system_default ['attach_image_thumb_quality'], intval($system_default ['attach_watermark_place']) );
							} else {
								Image::waters ( $default_options ['save_path'] .  $u['savename'], 1, "","", $system_default ['attach_image_thumb_quality'], intval($system_default ['attach_watermark_place']), $system_default ['attach_watermark_txt'], $system_default ['attach_watermark_fontsize'], './Public/font/simhei.ttf' );
							}
						}
					}
					
					unset($map);
				}
			}
			//输出信息
			$return['status']	=	true;
			$return['info']		=	$infos;
			//上传成功，返回信息
			return	$return;
    	}
	}
	
	//直接直接保存文件到附件表
	public function addFile($attach_type='attach',$attach_file) {

		//获取系统配置
		$system_default = model('Data')->lget('attach');
		if ( empty($system_default['attach_path_rule']) || empty($system_default['attach_max_size']) || empty($system_default['attach_allow_extension']) ) {
			$data['attach_path_rule']		 = 'Y/md/H/';
			$data['attach_max_size']		 = '2'; // 默认2M
			$data['attach_allow_extension']  = 'jpg,gif,png,jpeg,bmp,zip,rar,doc,xls,ppt,docx,xlsx,pptx,pdf';
			model('Data')->lput('attach', $data);
			$system_default = $data;
		}

		//获取文件信息
        if(!file_exists($attach_file)) {

			//上传失败，返回错误
			$return['status']	=	false;
			$return['info']		=	'原始文件不存在';
			return	$return;

		}else{

			//读取附件大小
			$file['size']	=	filesize($attach_file);
			$file['hash']	=	md5_file($attach_file);

			//读取附件名称、后缀名
			if(function_exists('pathinfo')){
				$fileinfo	=	pathinfo($attach_file);
				$file['name']		=	$fileinfo['basename'];
				$file['extension']	=	$fileinfo['extension'];
			}else{
				$file['name']	=	basename($attach_file);
				preg_match('|\.(\w+)$|', $file['name'], $file['extension']);
			}

			//读取附件类型
			if(function_exists('mime_content_type')){
				$file['type']	=	mime_content_type($attach_file);
			}elseif(in_array(strtolower($file['extension']),array('jpeg','jpg','gif','png','bmp'))){
				$file['type']	=	'image/'.$file['extension'];
			}else{
				$file['type']	=	'text/'.$file['extension'];
			}
		}

		//载入默认规则
		$options =	array();
		$options['custom_path']	=	date($system_default['attach_path_rule']);
		$options['save_path']	=	UPLOAD_PATH.'/'.$options['custom_path'];
		$options['save_name']	=	uniqid().".".$file['extension'];
		$options['save_to_db']	=	true;

		//用户ID
		if( intval($options['uid'])==0 )	$options['uid']	= intval($_SESSION['mid']);

		//创建目录
		mkdir($options['save_path'],0777,true);
		
		if($this->isOpenYun() && $attach_type === "weibo_image"){
			$isopenyun = true;
			$res = $this-> uploadYunPic($attach_file,$options['save_name']);
		}else{
			$res = copy($attach_file,$options['save_path'].'/'.$options['save_name']);
		}
		//执行上传操作
        if(!$res) {

			//上传失败，返回错误
			$return['status']	=	false;
			$return['info']		=	'文件转移失败';
			return	$return;

		}else{

			//保存信息到附件表
			$map['attach_type']	=	$attach_type;
			$map['userId']		=	$options['uid'];
			$map['name']		=	$file['name'];
			$map['type']		=	$file['type'];
			$map['size']		=	$file['size'];
			$map['extension']	=	strtolower($file['extension']);
			$map['hash']		=	$file['hash'];
			$map['savepath']	=	$isopenyun ? $res : $options['custom_path'];
			$map['savename']	=	$options['save_name'];
			$map['uploadTime']	=	time();
			$aid		=	M('Attach')->add($map);
			$map['id']	=	intval($aid);
			$map['key']	=	0;
			$map['isopenyun']	=	$isopenyun ? true : false;
			if($isopenyun){
				$yunConfig = include SITE_PATH . '/apps/admin/Conf/yun.php';
				$imageurl = str_replace('{upyun}',$yunConfig['picdomain'],$res).$options['save_name'];
				$site = getimagesize($imageurl);
				if(!empty($site)){
					$map['imagewidth'] = $site[0];
					$map['imageheight'] = $site[1];
				}
			}
			//上传成功，输出信息
			$return['status']	=	true;
			$return['info']		=	$map;
			return	$return;

    	}
	}
	
	/**
	 * 将图片上传到云
	 * @param unknown_type $pic 本地图片路径
	 * @param unknown_type $savename 图片名称
	 * @return boolean|string
	 */
	public function uploadYunPic($pic,$savename) {
		if (file_exists ( $pic )) {
			$yunConfig = include SITE_PATH . '/apps/admin/Conf/yun.php';
			import ( 'ORG.Upyun.upyun' );
			if (empty ( $yunConfig ['picbucket'] ) || empty ( $yunConfig ['yunname'] ) || empty ( $yunConfig ['yunpass'] )) {
				return false;
				exit ();
			}
			$upyun = new UpYun ( $yunConfig ['picbucket'], $yunConfig ['yunname'], $yunConfig ['yunpass'] );

			$fh = fopen ( $pic, 'r' );
			$photoPath = '/photo/' . intval($_SESSION['mid']) . '/' . date ( 'Y/m/d/' );
			$upyun->writeFile ( $photoPath. $savename, $fh, True ); // 返回一个布尔值
			fclose ( $fh );
			unlink ( $pic );
			return '{upyun}'.$photoPath;
		} else {
			return false;
		}
	}
	
	/**
	 * 上传文件到又拍云
	 * @param unknown_type $uid
	 */
	public function uploadUpYun($type="image",$configfilepath='/apps/admin/Conf/yun.php') {
		$yunConfig = include SITE_PATH . $configfilepath;
		if ( $yunConfig ['openyun'] !== "1") 
			return false;
		if ( empty ( $_FILES['imgFile'] )) 
			return false;
		$system_default = $this->getSystemDefault ();
		if ($type=="image" || $type == "photo"){
			$upyunbucket = $yunConfig ['picbucket'];
			$upyundomain = $yunConfig ['picdomain'];
			$filepath = '/'.$type.'/';
		}else{
			$upyunbucket = $yunConfig ['filebucket'];
			$upyundomain = $yunConfig ['filedomain'];
			$filepath = '/'.$type.'/';
		}
		import ( 'ORG.Upyun.upyun' );
		if (empty ( $upyunbucket ) || empty ( $yunConfig ['yunname'] ) || empty ( $yunConfig ['yunpass'] )) {
			return false;
		}
		try {
			$upyun = new UpYun ( $upyunbucket, $yunConfig ['yunname'], $yunConfig ['yunpass'] );
			move_uploaded_file ( $_FILES ['imgFile'] ['tmp_name'], $_FILES ['imgFile'] ['name'] ); // 将上传图片移动到新的位置

			$fh = fopen ( $_FILES ['imgFile'] ['name'], 'r' );
			//获得文件扩展名
			$temp_arr = explode(".", $_FILES ['imgFile'] ['name']);
			$file_ext = array_pop($temp_arr);
			$file_ext = trim($file_ext);
			$file_ext = strtolower($file_ext);
			$new_file_name = date("YmdHis") . rand(10000, 99999) . '.' . $file_ext;
			$photoPath = $filepath . intval($_SESSION['mid']) . '/' . date ( $system_default ['attach_path_rule'] ). $new_file_name;
			$upyun->writeFile ( $photoPath, $fh, True ); // 返回一个布尔值
			fclose ( $fh );
			unlink ( $_FILES ['imgFile'] ['name'] );
			return $upyundomain.$photoPath;
		} catch (Exception $e) {
			return false;
		}
	}
	
	/**
	 * 删除upyun上图片
	 * @param unknown_type $photoPath
	 */
	public function deleteUpYunFile($photoPath=null) {
		$yunConfig = include SITE_PATH . '/apps/admin/Conf/yun.php';
		if ( $yunConfig ['openyun'] !== "1")
			return false;
		if ( empty ( $photoPath ))
			return false;
		import ( 'ORG.Upyun.upyun' );
		if (empty ( $yunConfig ['picbucket'] ) || empty ( $yunConfig ['yunname'] ) || empty ( $yunConfig ['yunpass'] )) {
			return false;
		}
		try {
			$upyun = new UpYun ( $yunConfig ['picbucket'], $yunConfig ['yunname'], $yunConfig ['yunpass'] );
			$upyun->deleteFile ( $photoPath ); 
			return true;
		} catch (Exception $e) {
			return false;
		}
	}
	
	/**
	 * 是否开启云
	 */
	public function isOpenYun($configfilepath='/apps/admin/Conf/yun.php') {
		$yunConfig = include SITE_PATH . $configfilepath;
		return  $yunConfig ['openyun'] === "1" ? true : false;
	}
	
	/**
	 * 获取后台上传配置
	 */
	public function getSystemDefault() {
		$system_default = model('Data')->lget ( 'attach' );
		if (empty ( $system_default ['attach_path_rule'] ) || empty ( $system_default ['attach_max_size'] ) || empty ( $system_default ['attach_allow_extension'] )) {
			$data ['attach_path_rule'] = 'Y/m/d/';
			$data ['attach_max_size'] = '2'; // 默认2M
			$data ['attach_allow_extension'] = 'jpg,gif,png,jpeg,bmp,zip,rar,doc,xls,ppt,docx,xlsx,pptx,pdf';
			model('Data')->lput ( 'attach', $data );
			$system_default = $data;
		}
		return $system_default;
	}
		
}
?>